package com.cslg.ac.demo.controller.chat;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.cslg.ac.demo.constant.MessageType;
import com.cslg.ac.demo.constant.ResponseCode;
import com.cslg.ac.demo.entity.chat.Chat;
import com.cslg.ac.demo.entity.user.User;
import com.cslg.ac.demo.exception.ChatNotFoundException;
import com.cslg.ac.demo.exception.PermissionForbiddenException;
import com.cslg.ac.demo.service.chat.ChatService;
import com.cslg.ac.demo.service.message.MessageService;
import com.cslg.ac.demo.util.communicate.ResponseUtil;

import javax.servlet.http.HttpSession;

@Controller
public class ChatController {

	@Autowired
	private ChatService chatService;
	@Autowired
	private MessageService messageService;
	@Value("${maxChatLength}")
	private int maxChatLength; //200
	
	/**
	 * 聊天步骤如下
	 * 1.用户a用过 /chat/send 发送一条消息给用户b
	 * 2.用户b通过 /message/get 获取未读消息的 type 和 id
	 * 2.用户b通过 /chat/get 获取消息的详细内容
	 *
	 * @param targetId
	 * @param content
	 * @param out
	 */
	@RequestMapping(value="/chat/send", method=RequestMethod.POST)
	public void send(@RequestParam("id") int targetId, @RequestParam String content, PrintWriter out, HttpSession session)
	{
		User user = (User)session.getAttribute("user");
		if(targetId <= 0 || content.length() > maxChatLength)
		{
			ResponseUtil.responseCode(out, ResponseCode.PARAM_ILLEGAL);
			return;
		}
		int code;
		try
		{
			code = chatService.send(user.getId(), targetId, content);
			if(code == ResponseCode.REQUEST_SUCCESSED)
			{
				messageService.addMessage(user.getId(), MessageType.CHATTING, chatService.getLastInsertId());
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
			ResponseUtil.responseCode(out, ResponseCode.SERVER_ERROR);
			return;
		}
		ResponseUtil.responseCode(out, code);
	}
	
	@RequestMapping(value="/chat/get", method=RequestMethod.POST)
	public void get( @RequestParam("id") int id, PrintWriter out,HttpSession session)
	{
		User user = (User)session.getAttribute("user");
		if(id <= 0)
		{
			ResponseUtil.responseCode(out, ResponseCode.PARAM_ILLEGAL);
			return;
		}
		Chat chat;
		try
		{
			chat = chatService.get(user.getId(), id);
		}
		catch (ChatNotFoundException e)
		{
			ResponseUtil.responseCode(out, ResponseCode.CHAT_NOT_FOUND);
			return;
		}
		catch (PermissionForbiddenException e)
		{
			ResponseUtil.responseCode(out, ResponseCode.PERMISSION_FORBIDDEN);
			return;
		}
		catch (Exception e)
		{
			ResponseUtil.responseCode(out, ResponseCode.SERVER_ERROR);
			return;
		}
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("chat", chat);
		ResponseUtil.response(out, ResponseCode.REQUEST_SUCCESSED, param);
	}
	
	/**
	 * 获取聊天记录（分页）
	 * @param id  和谁的聊天记录
	 * @param offset
	 * @param num
	 * @param out
	 */
	@RequestMapping(value="/chat/getHistory", method=RequestMethod.POST)
	public void getHistory(@RequestParam("id") int id, @RequestParam int offset,
						   @RequestParam int num, PrintWriter out,HttpSession session) {
		User user = (User)session.getAttribute("user");
		if(id <= 0)
		{
			ResponseUtil.responseCode(out, ResponseCode.PARAM_ILLEGAL);
			return;
		}
		int[] ids;
		try
		{
			ids = chatService.get(user.getId(), id, offset, num);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			ResponseUtil.responseCode(out, ResponseCode.SERVER_ERROR);
			return;
		}
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("ids", ids);
		ResponseUtil.response(out, ResponseCode.REQUEST_SUCCESSED, param);
	}
	
}
